﻿/*******************************************************************************
 * Copyright © 2016 NFine.Framework 版权所有
 * Author: NFine
 * Description: NFine快速开发平台
 * Website：http://www.nfine.cn
*********************************************************************************/
using NFine.Code;
using NFine.Data;
using NFine.Domain._03_Entity.Biz;
using NFine.Domain._03_Entity.Weixin;
using NFine.Domain._04_IRepository.Biz;
using NFine.Domain.Entity.SystemManage;
using NFine.Domain.IRepository.SystemManage;
using NFine.Repository.Biz;
using NFine.Repository.SystemManage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NFine.Domain.Entity.Biz;
using NFine.Domain._02_ViewModel;
using NFine.Application.Biz;

namespace NFine.Application.SystemManage
{
    public class UserApp
    {
        private IUserRepository service = new UserRepository();
        private UserLogOnApp userLogOnApp = new UserLogOnApp();
        private IRoleRepository roleRepository = new RoleRepository();
        private IUserDetailRepository userDetailRepository = new UserDetailRepository();
        private IZhongZhuanPinJianRepository zhongZhuanPinJianRepository = new ZhongZhuanPinJianRepository();
        private ItemsDetailApp itemsDetailApp = new ItemsDetailApp();
        private IUserOrderRepository userOrderRepository = new UserOrderRepository();

        private UserDetailApp userDetailApp = new UserDetailApp();        
        //会员的角色ID;
        private string roleid = Configs.GetValue("MemberRoleId");
        /// <summary>
        /// 中转中心角色ID
        /// </summary>
        private string trid = Configs.GetValue("TransferCenterRoleId");

        public List<UserEntity> GetList(Pagination pagination, string keyword)
        {
            var expression = ExtLinq.True<UserEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.F_Account.Contains(keyword));
                expression = expression.Or(t => t.F_RealName.Contains(keyword));
                expression = expression.Or(t => t.F_MobilePhone.Contains(keyword));
            }
            expression = expression.And(t => t.F_Account != "admin");
            List<UserEntity> list = service.FindList(expression, pagination);
            foreach (var temp in list)
            {
                RoleEntity roleEntity = roleRepository.FindEntity(temp.F_RoleId);
                temp.RoleName = roleEntity.F_FullName;
            }
            return list;
        }

        private List<UserDetailEntity> GetUserDetailList(List<UserDetailEntity> list)
        {
            List<UserDetailEntity> list_result = new List<UserDetailEntity>();

            int i50 = list.Count / 50;
            int i_last = list.Count % 50;
            for (int i = 0; i <= i50; i++)
            {
                StringBuilder sbwhere = new StringBuilder();
                int count = i == i50 ? i_last : 50;
                for (var j = 0; j < count; j++)
                {
                    sbwhere.Append("'" + list[i * 50 + j].F_UserId + "',");
                }
                var listud2 = userDetailRepository.FindList("select * from biz_user_detail where F_ParentId in(" +
                                                            sbwhere.ToString(0, sbwhere.Length - 1) + ")");
                list_result.AddRange(listud2);
            }

            return list_result;
        }

        public List<UserEntity> GetListForTop(Pagination pagination)
        {
            var listuser=service.FindList("select * from sys_user");
            var listue=userDetailRepository.FindList("select * from biz_user_detail WHERE F_UserLevel=3 or F_UserLevel=-3");

            var listitem= itemsDetailApp.GetList("dd3f3919-e568-476c-b0d6-7618fa6557eb");
            var item = listitem.Find(t => t.F_ItemCode.Equals("3"));
            var productid = item.F_SimpleSpelling;

            var listorder = userOrderRepository.FindList("SELECT * FROM `biz_user_order` WHERE F_orderCode IN (SELECT F_OrderCode FROM `biz_order_items` WHERE F_productId='"+ productid + "' and F_OrderStatus>0)");
            List<UserEntity> res = new List<UserEntity>();
            Dictionary<string, int> dict = new Dictionary<string, int>();
            foreach (var order in listorder) {
                if (dict.ContainsKey(order.F_MemberId))
                {
                    dict[order.F_MemberId] += 1;
                }
                else
                    dict[order.F_MemberId] = 1;
            }
            foreach (var user in listuser) {
                if (dict.ContainsKey(user.F_Id)) {
                    res.Add(user);
                    user.F_ManagerId =  dict[user.F_Id]*2000+"元";
                    var ue= listue.Find(t => t.F_UserId == user.F_Id);
                    user.F_DutyId = ue.F_UserLevel+"";
                }
            }

            pagination.records = res.Count;
            return res.Skip((pagination.page - 1) * pagination.rows).Take(pagination.rows).ToList();
        }

        /// <summary>
        /// 根据列表中的用户详情获取列表中用户的相应用户信息
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<UserEntity> GetUserListByDetails(List<UserDetailEntity> list)
        {
            if (list.Count > 0)
            {
                int i50 = list.Count / 50;
                int i_last = list.Count % 50;
                List<UserEntity> list_result = new List<UserEntity>();
                for (int i = 0; i <= i50; i++)
                {
                    StringBuilder sbwhere = new StringBuilder();
                    int count = i == i50 ? i_last : 50;
                    if (count == 0)
                        break;
                    for (var j = 0; j < count; j++)
                    {
                        sbwhere.Append("'" + list[i * 50 + j].F_UserId + "',");
                    }
                    var listUser = service.FindList("select * from sys_user where F_Id in(" +
                                                    sbwhere.ToString(0, sbwhere.Length - 1) + ")");
                    list_result.AddRange(listUser);
                }
                return list_result;
            }
            else
            {
                return new List<UserEntity>();
            }
        }

        public List<UserInfoModel> GetList_WX(Pagination pagination)
        {
            var expression = ExtLinq.True<UserDetailEntity>();
            var u = OperatorProvider.Provider.GetCurrent();
            if (u != null)
            {
                expression = expression.And(t => t.F_ParentId == u.UserId);
                List<UserDetailEntity> listUd = userDetailRepository.FindList(expression, pagination);
                List<UserEntity> listUser = null;
                List<UserInfoModel> listTGM = new List<UserInfoModel>();
                if (listUd.Count > 0)
                {
                    foreach (var ud in listUd)
                    {
                        ud.F_ParentId = "0";
                    }
                    //加载用户基本信息
                    listUser = GetUserListByDetails(listUd);
                    for (int i = 0; i < listUd.Count; i++)
                    {
                        var ud = listUd[i];
                        UserEntity user = listUser.First(t => t.F_Id == ud.F_UserId);
                        UserInfoModel uInfo = new UserInfoModel();
                        uInfo.USERNICKNAME = user.F_RealName;
                        uInfo.USERHEAD = user.F_HeadIcon;
                        uInfo.USERNUMBER = user.F_Account;
                        uInfo.USERID = user.F_Id;
                        uInfo.USERTEL = user.F_MobilePhone;
                        uInfo.COUNT1 = uInfo.COUNT2 = uInfo.COUNT3 = 0;
                        var list=userDetailRepository.FindList(t => t.F_ParentId == user.F_Id);
                        foreach (var udone in list) {
                            if (udone.F_UserLevel == 1)
                            {
                                uInfo.COUNT1++;
                            }
                            else if (udone.F_UserLevel == 2)
                            {
                                uInfo.COUNT2++;
                            }
                            else if (udone.F_UserLevel == 3) {
                                uInfo.COUNT3++;
                            }
                        }
                                

                        uInfo.WECHATACCOUNT = userDetailApp.GetLevelText(ud);

                        listTGM.Add(uInfo);
                    }
                }
                return listTGM;
            }
            return null;
        }

        public int GetChildrenCount(string account)
        {
            return service.FindList(t => t.F_OrganizeId == account).Count;
        }

        public List<TreeGridModel> GetList(Pagination pagination)
        {
            var expression = ExtLinq.True<UserDetailEntity>();
            var u = OperatorProvider.Provider.GetCurrent();
            if (u != null && !u.IsSystem && !u.IsSys)
            {
                expression = expression.And(t => t.F_ParentId == u.UserId);
                List<UserDetailEntity> listUd = userDetailRepository.FindList(expression, pagination);
                List<UserEntity> listUser = null;
                List<TreeGridModel> listTGM = new List<TreeGridModel>();
                foreach (var ud in listUd)
                {
                    ud.F_ParentId = "0";
                }
                //加载用户基本信息
                listUser = GetUserListByDetails(listUd);
                for (int i = 0; i < listUd.Count; i++)
                {
                    var ue = listUser.First(t => t.F_Id == listUd[i].F_UserId);
                     ue.F_WeChat=(userDetailRepository.GetMemeberCount(listUd[i].F_UserId)+1).ToString();
                    //UserDetailEntity ud = new UserDetailEntity();
                    //ud.F_UserId=
                    //ue.F_DutyId=userDetailApp.GetLevelText()
                    TreeGridModel treeModel = new TreeGridModel();
                    bool hasChildren = listUd.Count(t => t.F_ParentId == listUd[i].F_UserId) == 0 ? false : true;
                    treeModel.id = listUd[i].F_UserId;
                    treeModel.isLeaf = hasChildren;
                    treeModel.parentId = listUd[i].F_ParentId;
                    treeModel.expanded = hasChildren;
                    treeModel.entityJson =ue.ToJson();
                    listTGM.Add(treeModel);
                }
                return listTGM;
            }
            else if (u != null && (u.IsSystem || u.IsSys))
            {
                expression = expression.And(t => t.F_ParentId == "0");
                List<UserDetailEntity> listUd = userDetailRepository.FindList(expression, pagination);
                List<UserEntity> listUser = null;
                List<TreeGridModel> listTGM = new List<TreeGridModel>();
                foreach (var ud in listUd)
                {
                    ud.F_ParentId = "0";
                }
                var list = GetUserDetailList(listUd);
                while (list.Count > 0)
                {
                    listUd.AddRange(list);
                    list = GetUserDetailList(list);
                }

                //加载用户基本信息
                listUser = GetUserListByDetails(listUd);
                for (int i = 0; i < listUd.Count; i++)
                {
                    var ue = listUser.First(t => t.F_Id == listUd[i].F_UserId);
                    ue.F_WeChat = (userDetailRepository.GetMemeberCount(listUd[i].F_UserId)+1).ToString();
                    var userid = ue.F_Id;
                    ue.F_DutyId = listUd[i].F_UserLevel+"";

                    TreeGridModel treeModel = new TreeGridModel();
                    bool hasChildren = listUd.Count(t => t.F_ParentId == listUd[i].F_UserId) == 0 ? false : true;
                    treeModel.id = listUd[i].F_UserId;
                    treeModel.isLeaf = hasChildren;
                    treeModel.parentId = listUd[i].F_ParentId;
                    treeModel.expanded = hasChildren;
                    treeModel.entityJson = ue.ToJson();
                    listTGM.Add(treeModel);
                }
                return listTGM;
            }
            else
            {
                return null;
            }
        }

        public UserEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public UserEntity GetFormInit()
        {
            UserEntity user = new UserEntity();
            user.F_Account = newAccount();
            user.F_OrganizeId = OperatorProvider.Provider.GetCurrent().UserCode;
            //user.F_RoleId = "4B2140D3-E61D-488E-ADF6-FF0EBCBC5D2C";
            return user;
        }
        /// <summary>
        /// 返回新的用户帐号，保证数据库中不存在的
        /// </summary>
        /// <returns></returns>
        private string newAccount()
        {
            string str = string.Empty;
            UserEntity ue;
            do
            {
                str = "RB" + Common.RndNum(6);
                ue = service.FindEntity(t => t.F_Account == str);
            }
            while (ue != null);
            return str;
        }

        public void DeleteForm(string keyValue)
        {
            service.DeleteForm(keyValue);
        }
        public void SubmitForm(UserEntity userEntity, UserLogOnEntity userLogOnEntity, string keyValue)
        {
            UserDetailEntity userDetail = null;
            if (!string.IsNullOrEmpty(keyValue))
            {
                userEntity.Modify(keyValue);
            }
            else
            {
                userEntity.F_EnabledMark = true;
                userEntity.Create();

                if (userEntity.F_RoleId == roleid || userEntity.F_RoleId == trid)//会员用户，中转中心用户
                {
                    var u = OperatorProvider.Provider.GetCurrent();

                    if (u != null)
                    {
                        userDetail = new UserDetailEntity();
                        userDetail.F_Id = Common.GuId();
                        userDetail.F_UserName = userEntity.F_RealName;
                        userDetail.F_TeamBonus = 0;
                        userDetail.F_TeamConsume = 0;
                        userDetail.F_UserConsume = 0;
                        userDetail.F_ManagerLevel = -1;
                        userDetail.F_UserLevel = -1;
                        if (u.RoleId != null && (u.RoleId.Equals(roleid) || u.RoleId.Equals(trid)))
                        {
                            userDetail.F_ParentId = u.UserId;
                            userDetail.F_ParentName = u.UserName;
                            var up = userDetailRepository.FindEntity(t => t.F_UserId == u.UserId);
                            if (up != null)
                                userDetail.F_TreeDepth = up.F_TreeDepth + 1;
                        }
                        else
                        {
                            userDetail.F_ParentId = "0";
                            userDetail.F_ParentName = "";
                            userDetail.F_TreeDepth = 1;
                        }
                    }
                }
            }
            service.SubmitForm(userEntity, userLogOnEntity, keyValue, userDetail);
        }
        public void UpdateForm(UserEntity userEntity)
        {
            service.Update(userEntity);
        }


        public int UpdateMemberInfo(UserEntity userEntity)
        {
            UserEntity temp = service.FindEntity(userEntity.F_Id);
            temp.F_RealName = userEntity.F_RealName;
            temp.F_Gender = userEntity.F_Gender;
            temp.F_DepartmentId = userEntity.F_DepartmentId;
            temp.F_MobilePhone = userEntity.F_MobilePhone;
            temp.F_Birthday = userEntity.F_Birthday;
            temp.F_WeChat = userEntity.F_WeChat;
            temp.F_Email = userEntity.F_Email;
            temp.F_Description = userEntity.F_Description;
            return service.Update(temp);
        }

        public UserEntity CheckLogin(string username, string password)
        {
            UserEntity userEntity = service.FindEntity(t => t.F_Account == username);
            if (userEntity != null)
            {
                if (userEntity.F_EnabledMark == true)
                {
                    UserLogOnEntity userLogOnEntity = userLogOnApp.GetForm(userEntity.F_Id);
                    string dbPassword = Md5.md5(DESEncrypt.Encrypt(password.ToLower(), userLogOnEntity.F_UserSecretkey).ToLower(), 32).ToLower();
                    if (dbPassword == userLogOnEntity.F_UserPassword)
                    {
                        DateTime lastVisitTime = DateTime.Now;
                        int LogOnCount = (userLogOnEntity.F_LogOnCount).ToInt() + 1;
                        if (userLogOnEntity.F_LastVisitTime != null)
                        {
                            userLogOnEntity.F_PreviousVisitTime = userLogOnEntity.F_LastVisitTime.ToDate();
                        }
                        userLogOnEntity.F_LastVisitTime = lastVisitTime;
                        userLogOnEntity.F_LogOnCount = LogOnCount;
                        userLogOnApp.UpdateForm(userLogOnEntity);
                        return userEntity;
                    }
                    else
                    {
                        throw new Exception("密码不正确，请重新输入");
                    }
                }
                else
                {
                    throw new Exception("账户被系统锁定,请联系管理员");
                }
            }
            else
            {
                throw new Exception("账户不存在，请重新输入");
            }
        }

        /// <summary>
        /// 获取系统所有的会员
        /// </summary>
        /// <returns></returns>
        public int GetAllMemberCount()
        {
            int result = 0;
            ///会员数量包括中转中心和会员，去掉无效的会员
            result = service.GetAllMemberCount(Configs.GetValue("MemberRoleId"), Configs.GetValue("TransferCenterRoleId"));
            return result;
        }

        /// <summary>
        /// 获取当前月新增的会员
        /// </summary>
        /// <returns></returns>
        public int GetCurMonthMemberCount()
        {
            int result = 0;
            result = service.GetAllMemberCurMonth(Configs.GetValue("MemberRoleId"), Configs.GetValue("TransferCenterRoleId"));
            return result;
        }

        public int GetMemberCountByDate(DateTime date)
        {
            return service.GetMemberCountByDate(date, Configs.GetValue("MemberRoleId"), Configs.GetValue("TransferCenterRoleId"));
        }

        /// <summary>
        /// 消费统计图表数据
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public List<View_UserChart> GetChartList(DateTime startTime, DateTime endTime)
        {
            List<View_UserChart> chartList = new List<View_UserChart>();
            for (DateTime dt = startTime; dt <= endTime; dt = dt.AddDays(1))
            {
                View_UserChart chartItem = new View_UserChart();
                chartItem.dateTime = dt;
                chartItem.memberCount = GetMemberCountByDate(dt);
                chartList.Add(chartItem);
            }

            return chartList;
        }

        public List<UserEntity> GetAllTransferCenter()
        {
            var expression = ExtLinq.True<UserEntity>();
            string roleId = Configs.GetValue("TransferCenterRoleId");
            expression = expression.And(t => t.F_RoleId == roleId);
            List<UserEntity> list = service.FindList(expression);
            return list;
        }
        /// <summary>
        /// 根据账户编号（FT000000）获取用户信息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public List<UserEntity> GetByAccount(string account)
        {
            var expression = ExtLinq.True<UserEntity>();
            expression = expression.And(t => t.F_Account == account);
            List<UserEntity> list = service.FindList(expression);
            return list;
        }

        public bool InitWeixinUser(WechatInfoEntity weinfo, UserEntity user, UserLogOnEntity userLogOnEntity)
        {
            user.F_Account = newAccount();
            user.F_OrganizeId = "RB" + weinfo.F_qrscene.ToString("000000");
            user.F_HeadIcon = weinfo.F_headimgurl;
            user.F_DutyId = "0";
            user.F_RoleId = Configs.GetValue("MemberRoleId");
            user.F_EnabledMark = true;
            user.F_openid = weinfo.F_openid;
            user.Create();
            UserDetailEntity userDetail = new UserDetailEntity();
            userDetail = new UserDetailEntity();
            userDetail.F_Id = Common.GuId();
            userDetail.F_UserName = user.F_RealName;
            userDetail.F_TeamBonus = 0;
            userDetail.F_TeamConsume = 0;
            userDetail.F_UserConsume = 0;
            userDetail.F_ManagerLevel = -1;

            if (weinfo.F_qrscene == 0)
            {
                userDetail.F_ParentId = "0";
                userDetail.F_ParentName = "";
                userDetail.F_TreeDepth = 1;
            }
            else
            {
                var u = GetByAccount(user.F_OrganizeId);
                if (u.Count == 0)
                {
                    userDetail.F_ParentId = "0";
                    userDetail.F_ParentName = "";
                    userDetail.F_TreeDepth = 1;
                }
                else
                {
                    userDetail.F_ParentId = u[0].F_Id;
                    userDetail.F_ParentName = u[0].F_RealName;
                    string uid = u[0].F_Id;
                    var up = userDetailRepository.FindEntity(t=>t.F_Id==uid);
                    if (up != null)
                    {
                        userDetail.F_TreeDepth = up.F_TreeDepth + 1;
                        user.F_CreatorUserId = up.F_Id;
                    }
                    else
                    {
                        userDetail.F_TreeDepth = 1;
                    }
                }
            }
            return service.SubmitForm(user, userLogOnEntity, string.Empty, userDetail) > 0;
        }

        /// <summary>
        ///  根据用户openid获取用户信息
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public UserEntity GetByOpenid(string openid)
        {
            var expression = ExtLinq.True<UserEntity>();
            expression = expression.And(t => t.F_openid == openid);
            List<UserEntity> list = service.FindList(expression);
            if (list.Count > 0)
                return list[0];
            else
                return null;
        }

        public bool IsExistDepartmentId(string departmentId, string userId = "")
        {
            int result = service.GetMemberCountByDepartmentIdAndUserId(departmentId, userId);

            return result > 0;
        }

        public int ChangePassword(string userId, string oldPassword, string newPassword)
        {
            int result = -1;

            //获取用户信息
            UserEntity userEntity = service.FindEntity(userId);
            if (userEntity == null)
                result = 0;

            //获取登录信息
            UserLogOnEntity userLogOnEntity = userLogOnApp.GetForm(userEntity.F_Id);
            string dbPassword = Md5.md5(DESEncrypt.Encrypt(Md5.md5(oldPassword, 32).ToLower(), userLogOnEntity.F_UserSecretkey).ToLower(), 32).ToLower();
            if (dbPassword == userLogOnEntity.F_UserPassword)
            {
                userLogOnApp.RevisePassword(newPassword, userLogOnEntity.F_Id);
                result = 1;
            }
            else
            {
                result = -1;
            }



            return result;
        }
        /// <summary>
        /// 获取中转中心的用户集合
        /// </summary>
        /// <returns></returns>
        public List<View_User_Zhzh> GetZhzhUser()
        {
            var list = service.FindList(t => t.F_RoleId == trid);
            var ls = new List<View_User_Zhzh>();
            if (list != null)
            {
                foreach (var user in list)
                {
                    View_User_Zhzh userzhzh = new View_User_Zhzh();
                    userzhzh.F_Id = user.F_Id;
                    userzhzh.F_RealName = user.F_RealName;
                    userzhzh.jfcount = zhongZhuanPinJianRepository.GetZhZhJF(user.F_Id);
                    ls.Add(userzhzh);
                }
            }
            return ls;
        }
        public bool ReSetUserLevel(string uid,int userlevel) {
            var ud = userDetailRepository.FindEntity(t=>t.F_UserId==uid);
            ud.F_UserLevel = userlevel;
            var u = GetForm(uid);
            u.F_jihuoTime = DateTime.Now;
            return service.UpdateUser(ud, u);
        }
        /// <summary>
        /// 退还用户押金，设置角色为-3
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool ReturnYaJin(string uid)
        {
            var ud = userDetailRepository.FindEntity(t => t.F_UserId == uid);
            ud.F_UserLevel = -3;
            var u = GetForm(uid);
            u.F_jihuoTime = DateTime.Now;
            return service.UpdateUser(ud, u);
        }
    }
}
